﻿using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Text;
using System.Windows.Forms;
using Dashboard.Expense.Business;
using Infragistics.Win;
using Infragistics.Win.UltraWinGrid;
using System.Globalization;

namespace Dashboard.Expense
{
    public partial class FormAddExpenseForm : Form
    {
        /// <summary>
        /// Form.ID
        /// </summary>
        public int ID { get; set; }
        /// <summary>
        /// Form.FormNo
        /// </summary>
        public int FormNo { get; set; }
        public string StaffNo { get; set; }
        public DataTable ExpenseDataTable { get; set; }

        private ValueList m_valueListCurrency = new ValueList();
        private ValueList m_valueListLocation = new ValueList();

        public FormAddExpenseForm()
        {
            InitializeComponent();
        }

        private void toolStripButtonDelete_Click(object sender, EventArgs e)
        {
            this.ultraGridMain.UpdateData();

            List<int> selectedIds = new List<int>();
            foreach (UltraGridRow row in this.ultraGridMain.Rows)
            {
                if (Convert.ToBoolean(row.Cells["Check"].Value) == true)
                {
                    selectedIds.Add(Convert.ToInt32(row.Cells["ID"].Value));
                }
            }

            if (selectedIds.Count == 0)
            {
                MessageBox.Show(this, "No data selected.", "Info", MessageBoxButtons.OK, MessageBoxIcon.Information);
                return;
            }

            if (MessageBox.Show(this, "Are you sure to delete selected records?", "Confirm",
                    MessageBoxButtons.YesNo, MessageBoxIcon.Question) == System.Windows.Forms.DialogResult.Yes)
            {
                try
                {
                    this.Cursor = Cursors.WaitCursor;

                    Exp_ExpenseForm eef = new Exp_ExpenseForm();
                    foreach (var id in selectedIds)
                    {
                        eef.DeleteExpenseItem(id);
                    }

                    MessageBox.Show(this, "Delete successfully.", "Info", MessageBoxButtons.OK, MessageBoxIcon.Information);

                    this.LoadFormLineInfo();
                }
                catch (Exception ex)
                {
                    MessageBox.Show(this, ex.Message, "Error", MessageBoxButtons.OK, MessageBoxIcon.Error);
                }
                finally
                {
                    this.Cursor = Cursors.Default;
                }
            }
        }

        private void toolStripButtonSaveDetail_Click(object sender, EventArgs e)
        {
            this.ultraGridAddExpense.UpdateData();

            if (this.ultraGridAddExpense.Rows.Count == 0)
            {
                MessageBox.Show(this, "No data found.", "Information", MessageBoxButtons.OK, MessageBoxIcon.Information);
                return;
            }

            // From Time, To Time , Date 都得输入
            if (this.maskedTextBoxExpTimeFrom.Text.Trim() == ":")
            {
                MessageBox.Show(this, "Please input the [From Time] field.", "Info", MessageBoxButtons.OK, MessageBoxIcon.Information);
                this.maskedTextBoxExpTimeFrom.Focus();
                this.maskedTextBoxExpTimeFrom.SelectAll();
                return;
            }

            if (this.maskedTextBoxExpTimeTo.Text.Trim() == ":")
            {
                MessageBox.Show(this, "Please input the [To Time] field.", "Info", MessageBoxButtons.OK, MessageBoxIcon.Information);
                this.maskedTextBoxExpTimeTo.Focus();
                maskedTextBoxExpTimeTo.SelectAll();
                return;
            }

            try
            {
                this.Cursor = Cursors.WaitCursor;

                Exp_ExpenseForm eef = new Exp_ExpenseForm();
                Exp_ExpenseLimit eel = new Exp_ExpenseLimit();

                DateTime fromTime = DateTime.ParseExact(this.maskedTextBoxExpTimeFrom.Text, "HH:mm", new CultureInfo("en-US"));
                DateTime toTime = DateTime.ParseExact(this.maskedTextBoxExpTimeTo.Text, "HH:mm", new CultureInfo("en-US"));

                decimal amount = 0;
                decimal totalBaseAmount = 0;
                List<string> sqls = new List<string>();
                string sql = "";

                List<string> msg = new List<string>();
                foreach (UltraGridRow row in this.ultraGridAddExpense.Rows)
                {
                    if (row.Cells["Amount"].Value.ToString().Trim() != "")
                    {
                        if (!decimal.TryParse(row.Cells["Amount"].Value.ToString().Trim(), out amount))
                        {
                            MessageBox.Show(this, "Please input the correct amount.", "Information", MessageBoxButtons.OK, MessageBoxIcon.Information);
                            row.Cells["Amount"].Activate();
                            return;
                        }

                        // 只有Amount > 0的才保存，其他忽略
                        if (amount == 0)
                        {
                            continue;
                        }

                        if (string.IsNullOrEmpty(Convert.ToString(row.Cells["Currency"].Value)))
                        {
                            MessageBox.Show(this, "Please select the currency.", "Information", MessageBoxButtons.OK, MessageBoxIcon.Information);
                            row.Cells["Currency"].Activate();
                            return;
                        }

                        if (string.IsNullOrEmpty(Convert.ToString(row.Cells["Location"].Value)))
                        {
                            MessageBox.Show(this, "Please select the location.", "Information", MessageBoxButtons.OK, MessageBoxIcon.Information);
                            row.Cells["Location"].Activate();
                            return;
                        }

                        decimal exchangeRate = decimal.Parse(row.Cells["ExchangeRate"].Value.ToString());
                        if (exchangeRate == 0)
                        {
                            MessageBox.Show(this, "Can not get the exchange rate.", "Information", MessageBoxButtons.OK, MessageBoxIcon.Information);
                            row.Cells["ExchangeRate"].Activate();
                            return;
                        }

                        // 保存
                        totalBaseAmount += amount * exchangeRate;

                        // 一系列的check，用一个list放所有的消息，最后一次性show出来
                        DataTable feeLimit = eel.GetExpenseLimit(this.comboBoxAppTypes.Text, row.Cells["FeeCode"].Value.ToString(), Convert.ToString(row.Cells["Location"].Value), this.textBoxPosition.Text, this.textBoxLevel.Text);
                        if (feeLimit.Rows.Count > 0)
                        {
                            // 有维护限额
                            // 先判断是否有限定时间，如果有，则检查当前时间是否符合区间
                            string fromTimeLimit = Convert.ToString(feeLimit.Rows[0]["FromTime"].ToString());
                            string toTimeLimit = Convert.ToString(feeLimit.Rows[0]["ToTime"].ToString());
                            if (!string.IsNullOrEmpty(fromTimeLimit) && !string.IsNullOrEmpty(toTimeLimit))
                            {
                                if (DateTime.ParseExact(fromTimeLimit, "HH:mm:ss", new CultureInfo("en-US")) < fromTime ||
                                    DateTime.ParseExact(toTimeLimit, "HH:mm:ss", new CultureInfo("en-US")) > toTime)
                                {
                                    msg.Add(string.Format("Expense [{0}] is out of time limit.", row.Cells["FeeCode"].Value.ToString()));
                                }
                            }

                            // 检查当前金额是否符合额度
                            decimal valueLimit = decimal.Parse(feeLimit.Rows[0]["LimitValue"].ToString());
                            decimal rateLimit = new Exp_ExchangeRate().GetExchangeRate(feeLimit.Rows[0]["Currency"].ToString(), this.textBoxBaseCurrency.Text);
                            decimal valueLimitBase = Math.Round(valueLimit * rateLimit, 2);
                            if (valueLimitBase < Math.Round(amount * exchangeRate, 2))
                            {
                                msg.Add(string.Format("Expense [{0}] goes beyond the amount limit [{1}].", row.Cells["FeeCode"].Value.ToString(), feeLimit.Rows[0]["Currency"].ToString() + " " + valueLimit));
                            }
                        }

                        sql = @"insert into exp_formdetail(formno,apptypecode,feecode,expensedate,fromtime,
                                                            totime,location,amount,currency,exchangerate,
                                                            comments,hasinvoice,insertdate,updateddate)
                                VALUES('{0}','{1}','{2}','{3}','{4}',
                                        '{5}','{6}',{7},'{8}',{9},
                                        '{10}','{11}',getdate(),getdate()) ";

                        bool receiptStatus = Convert.ToBoolean(row.Cells["HasInvoice"].Value) == true ? true : false;

                        sql = string.Format(sql, this.FormNo, this.comboBoxAppTypes.Text, row.Cells["FeeCode"].Value.ToString(),
                                                 this.dateTimeExpDateFrom.Value.ToString("yyyy-MM-dd"), fromTime.ToString("HH:mm"),
                                                 toTime.ToString("HH:mm"), Convert.ToString(row.Cells["Location"].Value),
                                                 amount, Convert.ToString(row.Cells["Currency"].Value), exchangeRate,
                                                 Convert.ToString(row.Cells["Comments"].Value), receiptStatus);

                        sqls.Add(sql);
                    }
                }

                if (msg.Count > 0)
                {
                    if (MessageBox.Show(this, "There are some expenses beyond the limit, are you sure to continue?" 
                                                + Environment.NewLine + string.Join(Environment.NewLine, msg.ToArray()), 
                                                "Confirmm", MessageBoxButtons.YesNo, MessageBoxIcon.Question) 
                        == System.Windows.Forms.DialogResult.No)
                    {
                        return;
                    }
                }

                eef.InsertExpenseItems(sqls, totalBaseAmount, this.ID);

                MessageBox.Show(this, "Expense items saved successfully.", "Info", MessageBoxButtons.OK, MessageBoxIcon.Information);

                toolStripButtonReset_Click(null, null);
                this.LoadFormHeadInfo();
                this.LoadFormLineInfo();
            }
            catch (Exception ex)
            {
                MessageBox.Show(this, ex.Message, "Error", MessageBoxButtons.OK, MessageBoxIcon.Error);
            }
            finally
            {
                this.Cursor = Cursors.Default;
            }
        }

        private void toolStripButtonSave_Click(object sender, EventArgs e)
        {
            // 保存表单
            if (this.textBoxFormName.Text.Trim() == "")
            {
                MessageBox.Show(this, "Please input the report name.", "Information", MessageBoxButtons.OK, MessageBoxIcon.Information);
                this.textBoxFormName.Focus();
                return;
            }

            decimal cash = 0;
            if (this.textBoxCash.Text.Trim() != "")
            {
                if (!decimal.TryParse(this.textBoxCash.Text.Trim(), out cash))
                {
                    MessageBox.Show(this, "Please input correct number.", "Information", MessageBoxButtons.OK, MessageBoxIcon.Information);
                    this.textBoxCash.Focus();
                    return;
                }
            }

            try
            {
                this.Cursor = Cursors.WaitCursor;

                string formName = this.textBoxFormName.Text.Trim();
                string staffNo = this.comboBoxStaffNo.Text;
                decimal totalAmount = decimal.Parse(this.textBoxTotalAmount.Text);
                decimal advanceCash = cash;
                decimal reimbursement = totalAmount - advanceCash;
                string comments = this.textBoxComments.Text.Trim();

                Exp_ExpenseForm eef = new Exp_ExpenseForm();
                string sql = "";
                if (this.ID == 0)
                {
                    // Add
                    this.FormNo = eef.GetNextFormNo();
                    sql = @"insert into exp_formhead(formno,staffno,formname,totalexpense,advancecash,reimbursement,comments,insertdate,updateddate,Createuser)
                            VALUES ('{0}','{1}','{2}',{3},{4},{5},'{6}',getdate(),getdate(),'{7}')";
                    sql = string.Format(sql, this.FormNo, staffNo, formName.Replace("'", "''"),
                                        totalAmount, advanceCash, reimbursement, comments.Replace("'", "''"),CommonBusiness.GetCurrentLoginUser());

                    this.ID = eef.InsertForm(sql, this.FormNo);

                    this.InitControl();
                }
                else
                {
                    // Update
                    sql = @"update exp_formhead 
                               set formname='{0}', totalexpense={1},advancecash={2},
                                   reimbursement={3},comments='{4}',updateddate=getdate() 
                             where ID = {5}";

                    sql = string.Format(sql, formName.Replace("'", "''"), totalAmount, advanceCash,
                                            reimbursement, comments.Replace("'", "''"), this.ID);

                    eef.UpdateForm(sql);

                    this.LoadFormHeadInfo();
                }

                MessageBox.Show(this, "Report save successfully.", "Info", MessageBoxButtons.OK, MessageBoxIcon.Information);
            }
            catch (Exception ex)
            {
                MessageBox.Show(this, ex.Message, "Error", MessageBoxButtons.OK, MessageBoxIcon.Error);
            }
            finally
            {
                this.Cursor = Cursors.Default;
            }
        }

        private void toolStripButtonCancel_Click(object sender, EventArgs e)
        {
            this.Close();
        }

        private void ultraGridMain_InitializeLayout(object sender, Infragistics.Win.UltraWinGrid.InitializeLayoutEventArgs e)
        {
            // 自适应列宽
            e.Layout.AutoFitStyle = Infragistics.Win.UltraWinGrid.AutoFitStyle.None;
            // 是否允许调整列宽
            e.Layout.Override.AllowColSizing = AllowColSizing.Free;
            // 是否允许移动栏位顺序
            e.Layout.Override.AllowColMoving = AllowColMoving.NotAllowed;

            // 设置Grid的Split窗口个数，建议设置为1--不允许Split
            e.Layout.MaxColScrollRegions = 1;
            e.Layout.MaxRowScrollRegions = 1;

            // 冻结列
            e.Layout.UseFixedHeaders = false;

            // 排序
            e.Layout.Override.HeaderClickAction = Infragistics.Win.UltraWinGrid.HeaderClickAction.SortSingle;

            // 不允许删除
            e.Layout.Override.AllowDelete = DefaultableBoolean.False;

            // 滚动提示
            // e.Layout.Bands[0].ScrollTipField = "";

            // 隐藏不需要显示的列
            e.Layout.Bands[0].Columns["ID"].Hidden = true;
            e.Layout.Bands[0].Columns["FormNo"].Hidden = true;
            e.Layout.Bands[0].Columns["InsertDate"].Hidden = true;
            e.Layout.Bands[0].Columns["UpdatedDate"].Hidden = true;

            for (int i = 0; i < e.Layout.Bands[0].Columns.Count; i++)
            {
                if (e.Layout.Bands[0].Columns[i].Key != "Check")
                {
                    e.Layout.Bands[0].Columns[i].CellActivation = Activation.NoEdit;
                }
                else
                {
                    e.Layout.Bands[0].Columns[i].CellActivation = Activation.AllowEdit;
                }
            }
        }

        private void FormAddExpenseForm_Load(object sender, EventArgs e)
        {
            try
            {
                BindStaffNoList();
                // 加载默认币别
                this.LoadBaseCurrency();

                // 加载ApplicationType
                this.LoadApplicationTypes();

                // 加载Location信息
                this.LoadLocations();

                // 加载Currency信息
                this.LoadCurrency();

                this.InitControl();

                if (this.ID == 0)
                {
                    // 加载Personal Information
                    this.LoadPersonalInformation(CommonBusiness.GetCurrentLoginUser());
                }
                else
                {
                    this.LoadPersonalInformation(this.StaffNo);
                    // Load Form Information & Expense List
                    this.LoadFormHeadInfo();
                    this.LoadFormLineInfo();
                }

                // 初始化数据源
                this.GenerateExpenseListDataSource();

                this.tabControl1.SelectedIndex = 0;
                this.toolStripButtonDelete.Enabled = false;
                this.dateTimeExpDateFrom.Value = DateTime.Now.Date;
            }
            catch (Exception ex)
            {
                MessageBox.Show(this, ex.Message, "Error", MessageBoxButtons.OK, MessageBoxIcon.Error);                
            }
        }
        private void BindStaffNoList()
        {
            BusinessBase bb = new BusinessBase();
            DataTable staffs = bb.GetStaffNo();

            this.comboBoxStaffNo.Items.Clear();
            this.comboBoxStaffNo.Text = string.Empty;
            this.comboBoxStaffNo.Items.Add("");

            foreach (DataRow row in staffs.Rows)
            {
                this.comboBoxStaffNo.Items.Add(row["staffno"].ToString());
            }
            bb = null;
        }
        private void LoadFormHeadInfo()
        {
            DataTable form = new Exp_ExpenseForm().GetFormHead(this.ID);
            if (form.Rows.Count > 0)
            {
                this.FormNo = int.Parse(form.Rows[0]["FormNo"].ToString());
                this.textBoxFormName.Text = form.Rows[0]["FormName"].ToString();
                this.textBoxComments.Text = form.Rows[0]["Comments"].ToString();
                this.textBoxTotalAmount.Text = form.Rows[0]["TotalExpense"].ToString();
                this.textBoxCash.Text = form.Rows[0]["AdvanceCash"].ToString();
                this.textBoxReimbursement.Text = form.Rows[0]["Reimbursement"].ToString();
            }
        }

        private void LoadFormLineInfo()
        {
            DataTable formLines = new Exp_ExpenseForm().GetFormLines(this.FormNo);
            this.ultraGridMain.DataSource = formLines;
            this.ultraGridMain.DataBind();
        }

        private void LoadPersonalInformation(string staffno)
        {
            //this.textBoxStaffNo.Text = CommonBusiness.GetCurrentLoginUser();
            if (this.comboBoxStaffNo.Items.Contains(staffno))
            {
                this.comboBoxStaffNo.Text = staffno;
            }
            else
            {
                return;
            }
            DataTable staff = new BusinessBase().GetStaffInfo(staffno);
            if (staff.Rows.Count == 0)
            {
                MessageBox.Show(this, "Can not find current user's information.", "Error", MessageBoxButtons.OK, MessageBoxIcon.Error);
            } 
            this.textBoxStaffName.Text = staff.Rows[0]["Name"].ToString();
            this.textBoxDepartment.Text = staff.Rows[0]["Dept"].ToString();
            this.textBoxCostCenter.Text = staff.Rows[0]["CostCenter"].ToString();
            this.textBoxLevel.Text = staff.Rows[0]["Level"].ToString();
            this.textBoxPosition.Text = staff.Rows[0]["Position"].ToString();
        }

        private void LoadBaseCurrency()
        {
            this.textBoxBaseCurrency.Text = new BusinessBase().GetBaseCurrency();
        }

        private void LoadCurrency()
        {
            DataTable currencies = new BusinessBase().GetCurrencies();

            this.comboBoxCurrency.Items.Clear();
            this.m_valueListCurrency.ValueListItems.Clear();

            this.comboBoxCurrency.Items.Add(this.textBoxBaseCurrency.Text);
            this.m_valueListCurrency.ValueListItems.Add(this.textBoxBaseCurrency.Text);

            foreach (DataRow row in currencies.Rows)
            {
                this.comboBoxCurrency.Items.Add(row["pvalue1"].ToString());

                this.m_valueListCurrency.ValueListItems.Add(row["pvalue1"].ToString());
            }
        }

        private void LoadLocations()
        {
            DataTable locations = new BusinessBase().GetLocations();

            this.comboBoxLocation.Items.Clear();
            this.m_valueListLocation.ValueListItems.Clear();
            foreach (DataRow row in locations.Rows)
            {
                this.comboBoxLocation.Items.Add(row["pvalue1"].ToString());

                this.m_valueListLocation.ValueListItems.Add(row["pvalue1"].ToString());
            }
        }

        private void LoadApplicationTypes()
        {
            Exp_ExpenseType eet = new Exp_ExpenseType();
            DataTable types = eet.QueryApplicationTypes();

            this.comboBoxAppTypes.Items.Clear();
            foreach (DataRow row in types.Rows)
            {
                this.comboBoxAppTypes.Items.Add(new ComboBoxItem() { Text = row["Code"].ToString(), Value = row["ID"].ToString() });
            }
        }

        private void InitControl()
        {
            if (this.ID == 0)
            {
                // Add
                this.ultraGroupBoxLine.Enabled = false;
            }
            else
            {
                // Edit
                this.ultraGroupBoxLine.Enabled = true;
            }
        }

        private void comboBoxAppTypes_SelectedIndexChanged(object sender, EventArgs e)
        {
            try
            {
                this.ClearDataSource();

                if (this.comboBoxAppTypes.SelectedIndex == -1)
                {
                    this.ultraGridAddExpense.DataSource = ExpenseDataTable;
                    this.ultraGridAddExpense.DataBind();
                    return;
                }
                // load expense
                DataTable expenses = new Exp_ExpenseType().QueryExpenseTypes(int.Parse(((ComboBoxItem)this.comboBoxAppTypes.SelectedItem).Value.ToString()));

                string selectedCurrency = this.comboBoxCurrency.Text;
                decimal exchangeRate;
                if (string.IsNullOrEmpty(selectedCurrency))
                {
                    exchangeRate = 0;
                }
                else
                {
                    exchangeRate = new Exp_ExchangeRate().GetExchangeRate(selectedCurrency, this.textBoxBaseCurrency.Text);
                    if (exchangeRate == 0)
                    {
                        MessageBox.Show(this, "Can not get the exchange rate.", "Information", MessageBoxButtons.OK, MessageBoxIcon.Information);
                        return;
                    }
                }

                // 初始化数据源
                foreach (DataRow row in expenses.Rows)
                {
                    // 针对餐费，需要自动计算出来费用，但有个问题，币别怎么处理？
                    // 暂时先不带  
                    ExpenseDataTable.Rows.Add(row["Code"].ToString(), this.comboBoxLocation.Text, 0, this.comboBoxCurrency.Text, true, "", exchangeRate);
                }

                ExpenseDataTable.AcceptChanges();

                this.ultraGridAddExpense.DataSource = ExpenseDataTable;
                this.ultraGridAddExpense.DataBind();
            }
            catch (Exception ex)
            {
                MessageBox.Show(this, ex.Message, "Error", MessageBoxButtons.OK, MessageBoxIcon.Error);                
            }
        }

        private void GenerateExpenseListDataSource()
        {
            ExpenseDataTable = new DataTable();
            ExpenseDataTable.Columns.Add("FeeCode", typeof(string));
            ExpenseDataTable.Columns.Add("Location", typeof(string));
            ExpenseDataTable.Columns.Add("Amount", typeof(decimal));
            ExpenseDataTable.Columns.Add("Currency", typeof(string));
            ExpenseDataTable.Columns.Add("HasInvoice", typeof(bool));
            ExpenseDataTable.Columns.Add("Comments", typeof(string));
            ExpenseDataTable.Columns.Add("ExchangeRate", typeof(decimal));

            ExpenseDataTable.AcceptChanges();
        }

        private void ClearDataSource()
        {
            ExpenseDataTable.Rows.Clear();
            ExpenseDataTable.AcceptChanges();
        }

        private void comboBoxLocation_SelectedIndexChanged(object sender, EventArgs e)
        {
            if (this.comboBoxLocation.Text != "")
            {
                if (this.ExpenseDataTable != null && this.ExpenseDataTable.Rows.Count > 0)
                {
                    foreach (DataRow row in this.ExpenseDataTable.Rows)
                    {
                        row["Location"] = this.comboBoxLocation.Text;
                    }

                    this.ExpenseDataTable.AcceptChanges();
                }
            }
        }

        private void comboBoxCurrency_SelectedIndexChanged(object sender, EventArgs e)
        {
            if (this.comboBoxCurrency.Text != "")
            {
                try
                {
                    // 获取ExchangeRate
                    decimal rate = new Exp_ExchangeRate().GetExchangeRate(this.comboBoxCurrency.Text, this.textBoxBaseCurrency.Text);
                    if (rate == 0)
                    {
                        MessageBox.Show(this, "Can not get the exchange rate.", "Information", MessageBoxButtons.OK, MessageBoxIcon.Information);
                        this.comboBoxCurrency.Focus();
                        this.textBoxExchangeRate.Text = "0";
                    }
                    else
                    {
                        this.textBoxExchangeRate.Text = rate.ToString();
                        if (this.ExpenseDataTable != null && this.ExpenseDataTable.Rows.Count > 0)
                        {
                            foreach (DataRow row in this.ExpenseDataTable.Rows)
                            {
                                row["Currency"] = this.comboBoxCurrency.Text;
                                row["ExchangeRate"] = rate;
                            }

                            this.ExpenseDataTable.AcceptChanges();
                        }
                    }
                }
                catch (Exception ex)
                {
                    MessageBox.Show(this, ex.Message, "Error", MessageBoxButtons.OK, MessageBoxIcon.Error);                    
                }
            }
        }

        private void toolStripButtonReset_Click(object sender, EventArgs e)
        {
            this.ClearDataSource();

            this.comboBoxAppTypes.SelectedIndex = -1;
        }

        private void dateTimeExpDateFrom_ValueChanged(object sender, EventArgs e)
        {
            // Do nothing
        }

        private void ultraGridAddExpense_InitializeLayout(object sender, InitializeLayoutEventArgs e)
        {
            // 自适应列宽
            e.Layout.AutoFitStyle = Infragistics.Win.UltraWinGrid.AutoFitStyle.None;
            // 是否允许调整列宽
            e.Layout.Override.AllowColSizing = AllowColSizing.Free;
            // 是否允许移动栏位顺序
            e.Layout.Override.AllowColMoving = AllowColMoving.NotAllowed;

            // 设置Grid的Split窗口个数，建议设置为1--不允许Split
            e.Layout.MaxColScrollRegions = 1;
            e.Layout.MaxRowScrollRegions = 1;

            // 冻结列
            e.Layout.UseFixedHeaders = false;

            // 排序
            e.Layout.Override.HeaderClickAction = Infragistics.Win.UltraWinGrid.HeaderClickAction.SortSingle;

            // 不允许删除
            e.Layout.Override.AllowDelete = DefaultableBoolean.False;

            // 滚动提示
            // e.Layout.Bands[0].ScrollTipField = "";

            e.Layout.Bands[0].Columns["FeeCode"].CellActivation = Activation.NoEdit;
            e.Layout.Bands[0].Columns["ExchangeRate"].CellActivation = Activation.NoEdit;

            e.Layout.Bands[0].Columns["Location"].CellActivation = Activation.AllowEdit;
            //e.Layout.Bands[0].Columns["Location"].Style = Infragistics.Win.UltraWinGrid.ColumnStyle.DropDownList;
            //e.Layout.Bands[0].Columns["Location"].ValueList = this.m_valueListLocation;

            e.Layout.Bands[0].Columns["Amount"].CellActivation = Activation.AllowEdit;
            e.Layout.Bands[0].Columns["Currency"].CellActivation = Activation.AllowEdit;
            e.Layout.Bands[0].Columns["Currency"].Style = Infragistics.Win.UltraWinGrid.ColumnStyle.DropDownList;
            e.Layout.Bands[0].Columns["Currency"].ValueList = this.m_valueListCurrency;

            e.Layout.Bands[0].Columns["Comments"].CellActivation = Activation.AllowEdit;
            e.Layout.Bands[0].Columns["HasInvoice"].CellActivation = Activation.AllowEdit;
        }

        private void textBoxCash_TextChanged(object sender, EventArgs e)
        {
            if (this.textBoxCash.Text.Trim() != "")
            {
                decimal cash = 0;
                if (decimal.TryParse(this.textBoxCash.Text.Trim(), out cash))
                {
                    this.textBoxReimbursement.Text = Convert.ToString(decimal.Parse(this.textBoxTotalAmount.Text) - cash);
                }
            }
        }

        private void tabControl1_SelectedIndexChanged(object sender, EventArgs e)
        {
            if (this.tabControl1.SelectedIndex == 0)
            {
                this.toolStripButtonDelete.Enabled = false;
            }
            else
            {
                this.toolStripButtonDelete.Enabled = true;
            }
        }

        private void ultraGridAddExpense_AfterCellListCloseUp(object sender, CellEventArgs e)
        {
            this.ultraGridAddExpense.UpdateData();
        }

        private void ultraGridAddExpense_AfterCellUpdate(object sender, CellEventArgs e)
        {
            if (e.Cell.Column.Key == "Currency")
            {
                try
                {
                    string fromCurrency = e.Cell.Row.Cells["Currency"].Value.ToString();

                    decimal rate = new Exp_ExchangeRate().GetExchangeRate(fromCurrency, this.textBoxBaseCurrency.Text);
                    e.Cell.Row.Cells["ExchangeRate"].Value = rate;
                    if (rate == 0)
                    {
                        MessageBox.Show(this, "Can not get the exchange rate.", "Information", MessageBoxButtons.OK, MessageBoxIcon.Information);
                    }
                }
                catch (Exception ex)
                {
                    MessageBox.Show(this, ex.Message, "Error", MessageBoxButtons.OK, MessageBoxIcon.Error);                    
                }
            }
        }

        private void comboBoxStaffNo_SelectedValueChanged(object sender, EventArgs e)
        {
            try
            {
                if (string.IsNullOrEmpty(this.comboBoxStaffNo.Text))
                    return;
                // 加载Personal Information
                this.LoadPersonalInformation(this.comboBoxStaffNo.Text);
            }
            catch (Exception ex)
            {
                MessageBox.Show(this, ex.Message, "Error", MessageBoxButtons.OK, MessageBoxIcon.Error);                
            }
        }
    }


}